package com.example.wyh.intelcheckbash.task;

import android.app.ActionBar;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.ExpandedMenuView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.AboutActivity;
import com.example.wyh.intelcheckbash.HttpUtil;
import com.example.wyh.intelcheckbash.LocalStorage;
import com.example.wyh.intelcheckbash.MainActivity;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.StatisticalCheckActivity;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by chen on 17/11/3.
 */

public class UploadCheckedTaskActivity extends AppCompatActivity {
    ProgressBar mProgressBar;
    String mDeviceToken;
    String mYhxtm;
    int mNeedUploadNumber;
    int mUploadedNumber = 0;
    int mSuccessNumber = 0;
    int mFallNumber = 0;
    JSONArray mAllNeedToUploadData;
    JSONObject mAllCompleteCheckedTask;

    boolean isUploadComplete = true;

    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(UploadCheckedTaskActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }

        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("上传结果");

        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.upload_title);

        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAllNeedToUploadData = null;
                mProgressBar = null;
                mDeviceToken = null;
                    UploadCheckedTaskActivity.this.finish();
            }
        });


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mAllNeedToUploadData = null;
            mProgressBar = null;
            mDeviceToken = null;
            this.finish();
        }
        return  true;
//        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uplaod);
        SysExitUtil.activityList.add(UploadCheckedTaskActivity.this);
        initActionBar();
        mProgressBar = (ProgressBar)findViewById(R.id.uploadProgressBar);
        mDeviceToken = getIntent().getStringExtra("deviceToken");
        mYhxtm = getIntent().getStringExtra("yhxtm");

        Button uploadResultButton = (Button)findViewById(R.id.upload_task_result_btn);
//        String key = "allCompleteCheckedTask_"+ LocalStorage.getUserXtm(UploadCheckedTaskActivity.this);
//        mAllCompleteCheckedTask = LocalStorage.getObject(UploadCheckedTaskActivity.this, key);
//        Log.e("allCompleteCheckedTask",mAllCompleteCheckedTask.toString());
//        String currentDate = HttpUtil.getCurrentDateString();
        mAllNeedToUploadData = new JSONArray();

        //更新版本号
        TextView upload_version_name = (TextView)findViewById(R.id.upload_version_name);
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
            String appVersionName = info.versionName; // 版本名
            upload_version_name.setText("颐达科技 "+appVersionName);
//            Log.e("currentVersionCode,appVersionName",currentVersionCode + " " + appVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch blockd
            e.printStackTrace();
        }

        try {
            mAllNeedToUploadData = getNeedUploadData();
            mNeedUploadNumber = mAllNeedToUploadData.length();
            TextView showPromptUploadNumber = (TextView)findViewById(R.id.prompt_upload_number_info);
            showPromptUploadNumber.setText("待上传数据："+mNeedUploadNumber+"条");
            if (mNeedUploadNumber == 0)
            {
                HttpUtil.showToast(UploadCheckedTaskActivity.this, "今天的巡检结果都已上传完成", 500);
//                Toast.makeText(UploadCheckedTaskActivity.this,"今天的巡检结果都已上传完成",Toast.LENGTH_SHORT).show();
                uploadResultButton.setText("重新上传结果");
            }
        }catch (Exception e)
        {
            HttpUtil.showToast(UploadCheckedTaskActivity.this, "今天没有要上传的结果", 500);
//            Toast.makeText(UploadCheckedTaskActivity.this,"今天没有要上传的结果",Toast.LENGTH_SHORT).show();
            uploadResultButton.setText("上传结果");
            uploadResultButton.setEnabled(false);
        }
        Log.e("hhhh",mAllNeedToUploadData.toString());
        uploadResultButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isUploadComplete == true)
                {
                    mUploadedNumber = 0;
                    mSuccessNumber = 0;
                    mFallNumber = 0;
                    Button uploadBtn = (Button)view;
                    String buttonText = "重新上传结果";
                    uploadBtn.setText(buttonText);
                    try {
                        if (mAllNeedToUploadData.length() == 0)
                        {
                            HttpUtil.showToast(UploadCheckedTaskActivity.this, "巡检结果都已上传完成", 500);
//                        Toast.makeText(UploadCheckedTaskActivity.this,"巡检结果都已上传完成",Toast.LENGTH_SHORT).show();
                        }else
                        {
                            isUploadComplete = false;
                            JSONObject uploadItem = mAllNeedToUploadData.getJSONObject(mUploadedNumber);
                            HttpUtil.requestNetForPostUploadAllData(mYhxtm,mDeviceToken,uploadItem,UploadCheckedTaskActivity.this,"UploadCheckedTaskActivity");
                        }
                    }catch (Exception e)
                    {
                    }
                }else
                {
                    showAlert("正在上传巡检结果...");
                }
            }
        });
    }

    public void showAlert(String msg)
    {
        LayoutInflater layoutInflater = LayoutInflater.from(UploadCheckedTaskActivity.this);
        final View layout = layoutInflater.inflate(R.layout.promot_alert,
                null);

        final AlertDialog alertDialog = new AlertDialog.Builder(UploadCheckedTaskActivity.this).setTitle("").setView(layout)
                .setPositiveButton("",  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setNegativeButton("", null).show();

        TextView alert_title = (TextView)layout.findViewById(R.id.promot_alert_title);
        alert_title.setText(msg);
        Button confirm = (Button)layout.findViewById(R.id.promot_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }


    public void updateProgressBar(final boolean isUploadSuccess)
    {
        Handler mainHander = new Handler(Looper.getMainLooper());
        mainHander.post(new Runnable() {
            @Override
            public void run() {
                //更新数据
                try{
//                    JSONArray allCheckedTask = mAllCompleteCheckedTask.getJSONArray(HttpUtil.getCurrentDateString());
//                    for (int i=0; i < allCheckedTask.length(); i++)
//                    {
//                        if (allCheckedTask.getJSONObject(i).getString("qysbxtm").equals(mAllNeedToUploadData.getJSONObject(mUploadedNumber).getString("qysbxtm")))
//                        {
//                            JSONObject itemTask = allCheckedTask.getJSONObject(i);
//                            itemTask.put("isUploadSuccess","1");
//                            allCheckedTask.put(i,itemTask);
//                            mAllCompleteCheckedTask.put(HttpUtil.getCurrentDateString(),allCheckedTask);
//                            String key = "allCompleteCheckedTask_"+ LocalStorage.getUserXtm(UploadCheckedTaskActivity.this);
//                            LocalStorage.saveObject(UploadCheckedTaskActivity.this,key,mAllCompleteCheckedTask);
//                            break;
//                        }
//                    }
                    mAllNeedToUploadData.getJSONObject(mUploadedNumber).put("isUploadSuccess",isUploadSuccess?"1":"0");
                    saveCompleteCheckInLocal(mAllNeedToUploadData.getJSONObject(mUploadedNumber));
                }catch (Exception e)
                {

                }
                if(isUploadSuccess){
                    mSuccessNumber ++;
                }else{
                    mFallNumber ++;
                }
                mUploadedNumber ++;
                if (mNeedUploadNumber>0)
                {
                    try {
                        mProgressBar.setProgress(100*mUploadedNumber/mNeedUploadNumber);
                    }
                    catch (Exception e)
                    {
                        Log.e("mProgressBar Exception",e.getMessage());
                    }

                }

                if (mUploadedNumber != mNeedUploadNumber)
                {
                    try {
                        mNeedUploadNumber = mAllNeedToUploadData.length();
                        JSONObject uploadItem = mAllNeedToUploadData.getJSONObject(mUploadedNumber);
                        HttpUtil.requestNetForPostUploadAllData(mYhxtm,mDeviceToken,uploadItem,UploadCheckedTaskActivity.this,"UploadCheckedTaskActivity");

                    }catch (Exception e)
                    {

                    }
                }
                else
                {
                    mAllNeedToUploadData = getLeftNeedUploadData();
                    mNeedUploadNumber = 0;
                    isUploadComplete = true;
                    HttpUtil.showToast(UploadCheckedTaskActivity.this, "上传完毕，成功上传"+mSuccessNumber +"条，还有"+ mFallNumber +"条待上传", 500);
                    mAllNeedToUploadData = getNeedUploadData();
                    mNeedUploadNumber = mAllNeedToUploadData.length();
                    TextView showPromptUploadNumber = (TextView)findViewById(R.id.prompt_upload_number_info);
                    showPromptUploadNumber.setText("待上传数据："+mNeedUploadNumber+"条");
//                    Toast.makeText(UploadCheckedTaskActivity.this,"巡检结果上传完成",Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    public JSONArray getLeftNeedUploadData()
    {
        JSONArray needUpload = new JSONArray();
        for (int i = 0; i < mAllNeedToUploadData.length(); i ++)
        {
            try {
                if (mAllNeedToUploadData.getJSONObject(i).getString("isUploadSuccess").equals("0"))
                {
                    needUpload.put(mAllNeedToUploadData.getJSONObject(i));
                }

            }catch (JSONException e)
            {

            }
        }
        return needUpload;
    }

    public  JSONArray getNeedUploadData(){

        JSONArray completeXmInfo = new JSONArray();
        TaskDbHelper taskDbHelper = new TaskDbHelper(UploadCheckedTaskActivity.this);
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
//        String query = "user_id = '" + LocalStorage.getUserXtm(UploadCheckedTaskActivity.this) + "'"
//                + " and time = '" + HttpUtil.getCurrentDateString() +"'"
//                + " and isUploadSuccess = '0'" ;
        String query = "user_id = '" + LocalStorage.getUserXtm(UploadCheckedTaskActivity.this) + "'"
                + " and isUploadSuccess = '0'" ;

        String[] columns = {"data"};
        Cursor cursor = null;
        try {
            cursor = db.query("complete_task", columns, query, null, null, null, null);
            while (cursor.moveToNext()) {
                if (cursor.getColumnIndex("data") > -1) {
                    String data = cursor.getString(cursor.getColumnIndex("data"));
                    try {
                        completeXmInfo.put(new JSONObject(data));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }

        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        return completeXmInfo;
    }

    public void saveCompleteCheckInLocal(JSONObject uploadEquipmentData) {
        String equipment_id=null;
        String equipmentStatus=null;
        try {
            equipment_id = uploadEquipmentData.getString("qysbxtm");
            equipmentStatus = uploadEquipmentData.getString("sbzt");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        TaskDbHelper taskDbHelper = new TaskDbHelper(UploadCheckedTaskActivity.this);
        SQLiteDatabase db = taskDbHelper.getWritableDatabase();

        ContentValues cv = new ContentValues();
        try {
            cv.put("isUploadSuccess",uploadEquipmentData.getString("isUploadSuccess"));
            cv.put("data",uploadEquipmentData.toString());
        }catch (JSONException e)
        {

        }
        int success = db.update("complete_task",cv,"equipment_id=? and equipmentStatus=? and user_id=? and time=?",new String[]{String.valueOf(equipment_id),
                String.valueOf(equipmentStatus),String.valueOf(LocalStorage.getUserXtm(UploadCheckedTaskActivity.this)),String.valueOf(HttpUtil.getCurrentDateString())});
        Log.e("success",success+"");
        db.close();
    }

}
